package com.fs.sys.service.impl;

import cn.hutool.core.lang.UUID;
import com.fs.common.exception.AppException;
import com.fs.sys.bean.dto.SysFileDTO;
import com.fs.common.ErrorCodes;
import com.fs.sys.service.FileUploadService;
import com.fs.sys.entityservice.SysFileEntityService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

/**
 * 本地文件服务
 *
 * @author  LiuQi 2025/4/7-9:47
 * @version V1.0
 **/
@Service
@ConditionalOnProperty(prefix = "file.upload", name = "type", havingValue = "local")
@Slf4j
public class LocalFileUploadService implements FileUploadService {
    @Value("${file.upload.local.dir}")
    private String dir;

    @Autowired
    private SysFileEntityService sysFileEntityService;

    @Value("${file.upload.local.prefix}")
    private String prefix;

    /**
     * 文件上传
     */
    @Override
    public SysFileDTO upload(String module, String fileName, byte[] bytes) {
        String dir = this.dir + "/" + module;
        if(!Files.exists(Path.of(dir))) {
            new File(dir).mkdir();
        }

        String fileId = UUID.fastUUID().toString(true);
        SysFileDTO sysFile = new SysFileDTO();
        sysFile.setModule(module);
        sysFile.setId(fileId);

        String suffix = fileName.substring(fileName.lastIndexOf("."));
        String objectName = module + "/" + LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        String filePath = this.dir + "/" + objectName;

        // 创建目录
        if (!Files.exists(Path.of(filePath))) {
            try {
                Files.createDirectory(Path.of(filePath));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        objectName +=  "/" + fileId + suffix;
        filePath += "/" + fileId + suffix;
        try {
            Files.write(Path.of(filePath), bytes, StandardOpenOption.CREATE);
        } catch (IOException e) {
            log.error("文件上传失败", e);
            throw AppException.of(ErrorCodes.BASE_FILE_UPLOAD_FAILED);
        }
        sysFile.setUrl(prefix + "/" + objectName);
        sysFile.setName(fileName);
        return sysFileEntityService.insert(sysFile);
    }

    @Override
    public byte[] getContent(String objectName) {
        String filePath = this.dir + "/" + objectName;
        try {
            return Files.readAllBytes(Path.of(filePath));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
